package com.banciyuan.bcywebview.biz.goods.store;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.ZhipinApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.view.gridview.HeaderGridView;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshHeaderGridView;
import com.banciyuan.bcywebview.biz.circles.smooth.CircleSmoothActivity;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.GoodsWork;


public class HotGoodsActivity extends BaseActivity {
    private ProgressbarHelper mProgressbarHelper;
    private PullToRefreshHeaderGridView refreshHeaderGridView;
    private HeaderGridView headerGridView;
    private RequestQueue mQueue;
    private HotGoodsAdapter mHotGoodsAdapter;
    private int page = 1;
    private boolean hasMore = true;
    private boolean loading = false;
    private List<GoodsWork> mGoodsWorkList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hotgoods);
        initArgs();
        initActionbar();
        initProgressbar();
        initUi();
        initAction();
        initData();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
    }

    @Override
    protected void initProgressbar() {
        View mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initActionbar() {
        ActionbarHelper mActionbarHelper = new ActionbarHelper(this, findViewById(R.id.base_action_bar));
        mActionbarHelper.setTitle(getString(R.string.hotsale_goods));
    }

    @Override
    protected void initUi() {
        refreshHeaderGridView = (PullToRefreshHeaderGridView) findViewById(R.id.grid_header_gridview_ptrhgv);
        headerGridView = refreshHeaderGridView.getRefreshableView();
    }

    @Override
    protected void initAction() {
        refreshHeaderGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<HeaderGridView>() {
            @Override
            public void onRefresh(PullToRefreshBase<HeaderGridView> refreshView) {
                if (!loading) {
                    loading = true;
                    hasMore = true;
                    page = 1;
                    initData();
                }
            }
        });
        refreshHeaderGridView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!loading && hasMore) {
                    loading = true;
                    page++;
                    initData();
                }
            }
        });
        headerGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    GoodsWork goodsWork = mGoodsWorkList.get(position);
                    Intent intent = new Intent(HotGoodsActivity.this, CircleSmoothActivity.class);
                    intent.putExtra(gotoUtil.INTENT_VALUE_ONE, goodsWork.getReal_name());
                    intent.putExtra(gotoUtil.INTENT_VALUE_TWO, goodsWork.getId());
                    intent.putExtra("from", 3);
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + ZhipinApi.getAllHotSellGoods();
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, HotGoodsActivity.this)) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        Gson gson = new Gson();
                        List<GoodsWork> goodsWorks = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<GoodsWork>>() {
                        }.getType());
                        isDataEmpty(goodsWorks);
                        dealGoodsWorks(goodsWorks);
                        onSuccess();
                    } catch (Exception e) {
                        onError();
                    }
                } else {
                    onError();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                onError();
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, this, params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        mQueue.add(stringRequest);
    }

    private void isDataEmpty(List<GoodsWork> goodsWorks) {
        if (goodsWorks.isEmpty())
            hasMore = false;
    }

    private void onSuccess() {
        loading = false;
        mProgressbarHelper.onSuccess();
        refreshHeaderGridView.onRefreshComplete();
    }

    private void onError() {
        loading = false;
        mProgressbarHelper.onFailed();
        refreshHeaderGridView.onRefreshComplete();
    }

    private void dealGoodsWorks(List<GoodsWork> goodsWorks) {
        if (page == 1)
            mGoodsWorkList.clear();
        mGoodsWorkList.addAll(goodsWorks);
        if (null == mHotGoodsAdapter) {
            mHotGoodsAdapter = new HotGoodsAdapter(mGoodsWorkList, this);
            headerGridView.setAdapter(mHotGoodsAdapter);
        } else {
            mHotGoodsAdapter.notifyDataSetChanged();
        }
    }
}
